package com.car.loan.project.system.service.impl;

import com.car.loan.common.constant.UserConstants;
import com.car.loan.common.enums.SwitchStatus;
import com.car.loan.common.enums.UserStatus;
import com.car.loan.common.exception.CustomException;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.common.utils.StringUtils;
import com.car.loan.framework.aspectj.DataScopeAspect;
import com.car.loan.framework.aspectj.lang.annotation.DataScope;
import com.car.loan.project.cm.util.bo.BusinessDeptBo;
import com.car.loan.project.cm.util.select.UserDataBaseSelect;
import com.car.loan.project.system.domain.SysRole;
import com.car.loan.project.system.domain.SysUser;
import com.car.loan.project.system.domain.SysUserDataAuthDept;
import com.car.loan.project.system.domain.SysUserDataAuthUser;
import com.car.loan.project.system.domain.SysUserRole;
import com.car.loan.project.system.mapper.SysRoleMapper;
import com.car.loan.project.system.mapper.SysUserDataAuthDeptMapper;
import com.car.loan.project.system.mapper.SysUserDataAuthUserMapper;
import com.car.loan.project.system.mapper.SysUserMapper;
import com.car.loan.project.system.mapper.SysUserRoleMapper;
import com.car.loan.project.system.service.ISysUserService;
import com.car.loan.project.tool.controller.BaseDataController.AdminBusinessList;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;


    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserDataAuthDeptMapper sysUserDataAuthDeptMapper;

    @Autowired
    private SysUserDataAuthUserMapper sysUserDataAuthUserMapper;


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }


    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserByUserDataBaseSelect(  AdminBusinessList adminBusinessList) {
        List<Integer> statusList = Lists.newArrayList();
        statusList.add(Integer.parseInt(UserStatus.OK.getCode()));
        if (null != adminBusinessList.getOf() && adminBusinessList.getOf() == SwitchStatus.PASS.status) {
            statusList.add(Integer.parseInt(UserStatus.DISABLE.getCode()));
        }
        UserDataBaseSelect userDataBaseSelect = new UserDataBaseSelect();
        userDataBaseSelect.setStatusList(statusList);
        userDataBaseSelect.setUserName(adminBusinessList.getName());
        userDataBaseSelect.setDeptId(adminBusinessList.getDepId());
        userDataBaseSelect.setDataScope(adminBusinessList.getDataScope());
        return userMapper.selectUserByUserDataBaseSelect(userDataBaseSelect);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
            if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
                return UserConstants.NOT_UNIQUE;
            }
            return UserConstants.UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        if (StringUtils.isNotEmpty(user.getEmail())) {
            SysUser info = userMapper.checkEmailUnique(user.getEmail());
            if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
                return UserConstants.NOT_UNIQUE;
            }
            return UserConstants.UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户与角色管理
        insertUserRole(user);
        // 用户权限 -自定义
        if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(user.getDataScope())) {
            insertUserDataAuth(user);
        }
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 用户权限 -自定义
        if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(user.getDataScope())) {
            insertUserDataAuth(user);
        }
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param avatar 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password, String passwordStrength) {
        return userMapper.resetUserPwd(userName, password, passwordStrength);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    private void insertUserDataAuth(SysUser user) {
        List<Integer> dataDeptIds = user.getDataDeptIds();
        if (!CollectionUtils.isEmpty(dataDeptIds)) {
            sysUserDataAuthDeptMapper.deleteSysUserDataAuthDeptById(user.getUserId());
            dataDeptIds.forEach(dataDeptId -> {
                SysUserDataAuthDept sysUserDataAuthDept = new SysUserDataAuthDept();
                sysUserDataAuthDept.setUserId(user.getUserId());
                sysUserDataAuthDept.setDeptId(dataDeptId);
                sysUserDataAuthDeptMapper.insertSysUserDataAuthDept(sysUserDataAuthDept);
            });
        }
        List<Long> dataUserIds = user.getDataUserIds();
        if (!CollectionUtils.isEmpty(dataUserIds)) {
            sysUserDataAuthUserMapper.deleteSysUserDataAuthUserById(user.getUserId());
            dataUserIds.forEach(dataUserId -> {
                SysUserDataAuthUser sysUserDataAuthUser = new SysUserDataAuthUser();
                sysUserDataAuthUser.setUserId(user.getUserId());
                sysUserDataAuthUser.setDataUserId(dataUserId);
                sysUserDataAuthUserMapper.insertSysUserDataAuthUser(sysUserDataAuthUser);
            });
        }
    }


    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        sysUserDataAuthUserMapper.deleteSysUserDataAuthUserById(userId);
        sysUserDataAuthDeptMapper.deleteSysUserDataAuthDeptById(userId);
        return userMapper.deleteUserById(userId);
    }
}
